package com.syni.mdd.yhd.common.all.service;

import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsDxCouponDao;
import com.syni.mdd.yhd.common.all.dto.requestDto.coupon.CouponReDto;
import com.syni.mdd.yhd.common.all.entity.BmsBusiness;
import com.syni.mdd.yhd.common.all.entity.BmsBusinessInfo;
import com.syni.mdd.yhd.common.all.entity.BmsDxCoupon;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @className BmsUserOperationLogService
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
public class BmsDxCouponService extends BaseService<BmsDxCoupon,Integer> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public final static Map<Integer,String> useWeekMap = new HashMap<>();

    static {
        useWeekMap.put(1,"周一");
        useWeekMap.put(2,"周二");
        useWeekMap.put(3,"周三");
        useWeekMap.put(4,"周四");
        useWeekMap.put(5,"周五");
        useWeekMap.put(6,"周六");
        useWeekMap.put(7,"周日");
    }

    @Autowired
    BmsDxCouponDao bmsDxCouponDao;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Autowired
    BmsBusinessinfoService bmsBusinessinfoService;

    @Autowired
    BmsPazarConditionService bmsPazarConditionService;

    @Override
    public BmsDxCouponDao getBaseDao() {
        return bmsDxCouponDao;
    }


    public Map<String, Object> findBussinessCoupon(Integer businessId, Integer pageNum, Integer pageSize) {
        Pageable pageable = BmsCommonService.getPageable(pageNum ,pageSize, Sort.Direction.DESC,"newTime");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("isOffline",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("bmsBusinessId",businessId);
        conditionMap.put("type",Constants.COUPON_SET);
        Page<BmsDxCoupon> bmsDxCouponPage = bmsDxCouponDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsDxCoupon> bmsDxCoupons = bmsDxCouponPage.getContent();
        //设置是否可用
        setIsUse(bmsDxCoupons);
        //整理星期
        setUserWeek(bmsDxCoupons);
        //设置商家
        setCouponBusiness(bmsDxCoupons);
        //判断线上买单信息
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.putAll(checkOnlinePayIsUser(bmsDxCoupons));
        userDataMap.put("isSetNum",bmsDxCouponPage.getTotalElements());
        return ResultMapHelper.success(bmsDxCoupons,userDataMap,"获取成功");
    }

    private Map<String,Object> checkOnlinePayIsUser(List<BmsDxCoupon> bmsDxCoupons) {
        //List<Integer> weekNums = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7}));
        Map<String,Object> canUseMap = new HashMap<>();
        canUseMap.put("onLineIsUse",Constants.COMMON_FLAG_TRUE_INT);
        /*if(bmsDxCoupons != null && bmsDxCoupons.size() > 0){
            for(BmsDxCoupon bmsDxCoupon : bmsDxCoupons){
                if(bmsDxCoupon.getIsUse() == Constants.COMMON_FLAG_TRUE_INT){
                    canUseMap.put("onLineIsUse",Constants.COMMON_FLAG_FALSE_INT);
                    break;
                }
            }
        }*/
        /*Set<Integer> weeks = new HashSet<>();
        if(bmsDxCoupons != null && bmsDxCoupons.size() > 0){
            for(BmsDxCoupon bmsDxCoupon : bmsDxCoupons){
                String[] useWeeks = bmsDxCoupon.getUseWeek().split("_");
                if(useWeeks.length > 0){
                    for(String use : useWeeks){
                        Integer canUseDate = Integer.parseInt(use);
                        weeks.add(canUseDate);
                        if(weekNums.contains(canUseDate)){
                            int index = weekNums.indexOf(canUseDate);
                            weekNums.remove(index);
                        }
                    }
                }
            }
        }
        //获取当前星期
        Date nowTime = new Date();
        int nowWeek = DateTimeUtils.getDayOfWeek(nowTime);
        if(!weeks.contains(nowWeek)){
            canUseMap.put("onLineIsUse",Constants.COMMON_FLAG_TRUE_INT);
        }
        //处理可用星期
        if(weekNums.size() > 0){
            String useWeekNum = StringUtils.join(weekNums,"_");
            BmsDxCoupon bmsDxCoupon = new BmsDxCoupon();
            bmsDxCoupon.setUseWeek(useWeekNum);
            List<BmsDxCoupon> bmsDxCouponses = new LinkedList<>();
            bmsDxCouponses.add(bmsDxCoupon);
            setUserWeek(bmsDxCouponses);
            canUseMap.put("onLineIsUseWeek",bmsDxCouponses.get(0).getUseWeekDisplay());
        }*/
        return canUseMap;
    }


    public void setCouponBusiness(List<BmsDxCoupon> bmsDxCoupons) {
        if(bmsDxCoupons != null && bmsDxCoupons.size() > 0){
            Set<Integer> businessIds = new HashSet<>();
            for(BmsDxCoupon bmsDxCoupon : bmsDxCoupons){
                //设置用户
                businessIds.add(bmsDxCoupon.getBmsBusinessId());
            }
            if(businessIds.size() > 0){
                Map<Integer, BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIds(businessIds);
                for(BmsDxCoupon bmsDxCoupon : bmsDxCoupons){
                    //设置用户
                    if(bmsBusinessMap.containsKey(bmsDxCoupon.getBmsBusinessId())){
                        bmsDxCoupon.setBmsBusiness(bmsBusinessMap.get(bmsDxCoupon.getBmsBusinessId()));
                    }
                }
            }
        }
    }

    public void setIsUse(List<BmsDxCoupon> bmsDxCoupons){
        if(bmsDxCoupons != null && bmsDxCoupons.size() > 0){
            for(BmsDxCoupon bmsDxCoupon : bmsDxCoupons){
                //先判断是否在使用日期内
                Date startTime = bmsDxCoupon.getStartTime();
                Date endTime = DateTimeUtils.addDay(bmsDxCoupon.getEndTime(),1);
                Date nowTime = new Date();
                logger.info("开始时间：" + startTime.toString());
                logger.info("结束时间：" + endTime.toString());
                logger.info("现在时间：" + nowTime.toString());

                if(!(startTime.getTime() <= nowTime.getTime() && nowTime.getTime() <= endTime.getTime())){
                    bmsDxCoupon.setIsUse(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
                    continue;
                }
                //判断是不是在星期内
                String[] useWeeks = bmsDxCoupon.getUseWeek().split("_");
                int dayOfWeek = DateTimeUtils.getDayOfWeek(nowTime);
                if(useWeeks.length > 0){
                    boolean ret = false;
                    for(String useWeek : useWeeks){
                        if(dayOfWeek == Integer.parseInt(useWeek)){
                            ret = true;
                            break;
                        }
                    }
                    if(!ret){
                        bmsDxCoupon.setIsUse(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
                        continue;
                    }
                }
                //判断是不是在可用的周期
                String useTime = bmsDxCoupon.getUseTime();
                if(StringUtils.isNotBlank(useTime)){
                    if(useTime.equals("营业时间可用")){
                       return;
                    }
                    //当前时分
                    String[] useTimes = useTime.split("-");
                    String nowTimeStr = DateTimeUtils.converDateToString(nowTime,DateTimeUtils.DATE_PATTERN_DAY);
                    String startTimeStr = nowTimeStr + " " + String.format("%s:00",useTimes[0]);
                    String endTimeStr = nowTimeStr + " " + String.format("%s:00",useTimes[1]);
                    long startTimes = DateTimeUtils.converStrToTimestamp(startTimeStr).getTime();
                    long endTimes = DateTimeUtils.converStrToTimestamp(endTimeStr).getTime();
                    if(!(startTimes < nowTime.getTime() && nowTime.getTime() < endTimes)){
                        bmsDxCoupon.setIsUse(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
                        continue;
                    }
                }
            }
        }
    }

    public void setUserWeek(List<BmsDxCoupon> bmsDxCoupons) {
        if(bmsDxCoupons != null && bmsDxCoupons.size() > 0){
            for(BmsDxCoupon bmsDxCoupon : bmsDxCoupons){
                System.out.println(bmsDxCoupon.getId());
                String[] userWeek = bmsDxCoupon.getUseWeek().split("_");
                int[] intUseWeek = Arrays.asList(userWeek).stream().mapToInt(Integer::parseInt).toArray();
                WebUtils.bubbleSort(intUseWeek);
                //处理连续显示逻辑
                LinkedList<Integer> count = new LinkedList<>();
                List<String> userWeekList = new LinkedList<>();
                if(intUseWeek.length > 0){
                    count.add(intUseWeek[0]);
                    for(int ii = 1;ii<intUseWeek.length;ii++){
                        if(intUseWeek[ii] - 1 == intUseWeek[ii - 1]){
                            count.add(intUseWeek[ii]);
                        }else {
                            //消耗队列
                            handUseWeekList(count,userWeekList,bmsDxCoupon);
                            count.add(intUseWeek[ii]);
                        }
                    }
                    handUseWeekList(count,userWeekList,bmsDxCoupon);
                }
                if(userWeekList.size() > 0){
                    //System.out.println(StringUtils.join(userWeekList,","));
                    bmsDxCoupon.setUseWeekDisplay(StringUtils.join(userWeekList,","));
                }
            }
        }
    }

    //消耗队列
    public void handUseWeekList(LinkedList<Integer> count,List userWeekList,BmsDxCoupon bmsDxCoupon){
        if(count.size() > 0){
            if(count.size() > 2){
                Integer start = count.getFirst();
                Integer end = count.getLast();
                userWeekList.add(useWeekMap.get(start) + "至"+ useWeekMap.get(end));
            }else {
                for(Integer op : count){
                    userWeekList.add(useWeekMap.get(op));
                }
            }
            count.clear();
        }
    }

    public Map<String, Object> deleteCoupon(Integer couponId) {
        BmsDxCoupon bmsDxCoupon = bmsDxCouponDao.findByIdAndIsDelete(couponId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxCoupon == null){
            return ResultMapHelper.result(ResultCode.CODE_COUPON_NO_EXIST,"该优惠券不存在！");
        }
        bmsDxCoupon.setIsDelete(Constants.COMMON_FLAG_TRUE_INT);
        bmsDxCouponDao.save(bmsDxCoupon);
        return ResultMapHelper.success(null,"删除成功");
    }

    public Map<String, Object> createBussinessCoupon(Map<String,Object> paramsMap) {
        final int MAX_SET_NUM = 5;
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer businessId = Integer.parseInt(paramsMap.get("business_id").toString());
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        //查询是否超过限制
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("bmsBusinessId",businessId);
        conditionMap.put("type",Constants.COUPON_SET);
        conditionMap.put("isOffline",Constants.COMMON_FLAG_FALSE_INT);
        int setNum = (int)bmsDxCouponDao.count(new SpecificationUtils(conditionMap));
        if(setNum >= MAX_SET_NUM){
            return ResultMapHelper.result(ResultCode.CODE_COUPON_SET_MAX,ResultMsg.CODE_COUPON_SET_MAX);
        }
        Integer payType = Integer.parseInt(paramsMap.get("pay_type").toString());
        String payContent = paramsMap.get("pay_content").toString();
        String useWeek = paramsMap.get("use_week").toString();
        String startTime = paramsMap.get("start_time").toString();
        String endTime = paramsMap.get("end_time").toString();
        String useTime = paramsMap.get("use_time").toString();
        Map<String,Object> check = checkCouponSetTimeIsEffective(startTime,endTime,useTime);
        if(!ResultCode.CODE_NORMAL.equals(check.get("status"))){
            return check;
        }
        Integer useScope = Integer.parseInt(paramsMap.get("use_scope").toString());
        Integer holidaysUseStatus = Integer.parseInt(paramsMap.get("holidays_use_status").toString());
        Integer isShareOther = Integer.parseInt(paramsMap.get("is_share_other").toString());
        Integer useNum = 0;
        if(paramsMap.containsKey("use_num") && StringUtils.checkNullAndEmpty(paramsMap.get("use_num"))){
            useNum = Integer.parseInt(paramsMap.get("use_num").toString());
        }
        String prodFreeServices = null;
        if(paramsMap.containsKey("prod_free_services") && StringUtils.checkNullAndEmpty(paramsMap.get("prod_free_services").toString())){
            prodFreeServices = paramsMap.get("prod_free_services").toString();
        }
        //查询是否有重复买单的优惠买单
        Map<String,Object> filterMap = new HashMap<>();
        filterMap.put("bmsBusinessId",businessId);
        filterMap.put("type",Constants.COUPON_SET);
        filterMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        filterMap.put("isOffline",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsDxCoupon> bmsDxCoupons = bmsDxCouponDao.findAll(new SpecificationUtils(filterMap));
        if(!checkDxCouponsIsSet(bmsDxCoupons,useWeek,startTime,endTime,useTime)){
            return ResultMapHelper.result(ResultCode.CODE_COUPON_IS_SET_REPEART,ResultMsg.CODE_COUPON_IS_SET_REPEART);
        }
        //开始创建买单
        BmsDxCoupon bmsDxCoupon = new BmsDxCoupon();
        bmsDxCoupon.setType(Constants.COUPON_SET);
        bmsDxCoupon.setPayType(payType);
        bmsDxCoupon.setPayContent(payContent);
        String[] useWeeks = useWeek.split("_");
        List<String> useWeekList = Arrays.asList(useWeeks);
        bmsDxCoupon.setUseWeek(StringUtils.join(useWeekList,"_"));
        bmsDxCoupon.setStartTime(DateTimeUtils.converStringToDate(startTime));
        bmsDxCoupon.setEndTime(DateTimeUtils.converStringToDate(endTime));
        bmsDxCoupon.setUseTime(useTime);
        bmsDxCoupon.setUseScope(useScope);
        bmsDxCoupon.setHolidaysUseStatus(holidaysUseStatus);
        bmsDxCoupon.setIsShareOther(isShareOther);
        bmsDxCoupon.setUseNum(useNum);
        bmsDxCoupon.setNewTime(new Date());
        bmsDxCoupon.setBmsBusinessId(businessId);
        bmsDxCoupon.setProdFreeServices(prodFreeServices);
        bmsDxCoupon.setIsOffline(Constants.COMMON_FLAG_FALSE_INT);
        bmsDxCoupon.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
        bmsDxCouponDao.save(bmsDxCoupon);
        bmsPazarConditionService.updatePazarConditionCouponData(businessId);
        return ResultMapHelper.success(null,ResultMsg.INSERT_SUCCESS);
    }

    private Map<String,Object> checkCouponSetTimeIsEffective(String startTime, String endTime, String useTime) {
        //检验时间
        Integer st = DateTimeUtils.converStrToInteger(startTime);
        Integer et = DateTimeUtils.converStrToInteger(endTime);
        if(st > et) {
            return ResultMapHelper.result(ResultCode.CODE_ERROR_03, "买单有效期填写有误");
        }
        //检测时间
        Date nowTime = new Date();
        String nowStr = DateTimeUtils.converDateToString(nowTime,DateTimeUtils.DATE_PATTERN_DAY);
        String[] checkUseTime = useTime.split("-");
        String startTimeStr = String.format("%s %s:00",nowStr,checkUseTime[0]);
        String endTimeStr = String.format("%s %s:00",nowStr,checkUseTime[1]);
        Integer startTimeStrd = (int)(DateTimeUtils.converStringToDate(startTimeStr,DateTimeUtils.DATE_PATTERN_TIMESTAMP).getTime() / 1000);
        Integer endTimeStrd = (int)(DateTimeUtils.converStringToDate(endTimeStr,DateTimeUtils.DATE_PATTERN_TIMESTAMP).getTime() / 1000);
        if(startTimeStrd.intValue() >= endTimeStrd.intValue()){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_03, "买单使用时间填写有误");
        }
        return ResultMapHelper.success();
    }

    private boolean checkDxCouponsIsSet(List<BmsDxCoupon> bmsDxCoupons, String useWeek, String startTime, String endTime, String useTime) {
        boolean ret = true;
        if(bmsDxCoupons != null && bmsDxCoupons.size() > 0){
            for(BmsDxCoupon bmsDxCoupon : bmsDxCoupons){
                Integer dxCouponStartTime = (int)(bmsDxCoupon.getStartTime().getTime() / 1000);
                Integer dxCouponEndTime = (int) (bmsDxCoupon.getEndTime().getTime() / 1000);
                Integer startTimes = (int)(DateTimeUtils.converStringToDate(startTime,DateTimeUtils.DATE_PATTERN_DAY).getTime() / 1000);
                Integer endTimes = (int)(DateTimeUtils.converStringToDate(endTime,DateTimeUtils.DATE_PATTERN_DAY).getTime() / 1000);
                if((startTimes >= dxCouponStartTime && startTimes <= dxCouponEndTime) ||
                        (endTimes >= dxCouponStartTime && endTimes <= dxCouponEndTime)) {
                    //判断星期是否重叠
                    List<String> bxUseWeeks = Arrays.asList(bmsDxCoupon.getUseWeek().split("_"));
                    List<String> useWeeks = Arrays.asList(useWeek.split("_"));
                    boolean isOverWeek = false;
                    if(bxUseWeeks.size() > 0){
                        for(String bxUseWeek : bxUseWeeks){
                            if(useWeeks.contains(bxUseWeek)){
                                isOverWeek = true;
                                break;
                            }
                        }
                    }
                    if(isOverWeek){
                        //判断使用时间是否重叠
                        String dxUseTime = bmsDxCoupon.getUseTime();
                        if(StringUtils.isNotBlank(useTime)){
                            if(!"营业时间可用".equals(useTime)){
                                //当前时分
                                String[] useTimes = dxUseTime.split("-");
                                Date nowTime = new Date();
                                String nowStr = DateTimeUtils.converDateToString(nowTime,DateTimeUtils.DATE_PATTERN_DAY);
                                String startTimeStr = String.format("%s %s:00",nowStr,useTimes[0]);
                                String endTimeStr = String.format("%s %s:00",nowStr,useTimes[1]);

                                String[] chUseTimes = useTime.split("-");
                                String chTimeStart =  String.format("%s %s:00",nowStr,chUseTimes[0]);
                                String chTimeEnd = String.format("%s %s:00",nowStr,chUseTimes[1]);
                                Integer startTimeStrd = (int)(DateTimeUtils.converStringToDate(startTimeStr,DateTimeUtils.DATE_PATTERN_TIMESTAMP).getTime() / 1000);
                                Integer endTimeStrd = (int)(DateTimeUtils.converStringToDate(endTimeStr,DateTimeUtils.DATE_PATTERN_TIMESTAMP).getTime() / 1000);
                                Integer chTimeStarts = (int)(DateTimeUtils.converStringToDate(chTimeStart,DateTimeUtils.DATE_PATTERN_TIMESTAMP).getTime() / 1000);
                                Integer chTimeEnds = (int)(DateTimeUtils.converStringToDate(chTimeEnd,DateTimeUtils.DATE_PATTERN_TIMESTAMP).getTime() / 1000);
                                /*if((chTimeStarts > startTimeStrd && chTimeStarts < endTimeStrd) ||
                                        (chTimeEnds > startTimeStrd && chTimeEnds < endTimeStrd)) {
                                    ret = false;
                                    break;
                                }*/
                                if(!(chTimeStarts > endTimeStrd || startTimeStrd > chTimeEnds)){
                                    if(!(endTimeStrd.intValue() == chTimeStarts.intValue()
                                            || chTimeEnds.intValue() == startTimeStrd.intValue())){
                                        ret = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return ret;
    }

    @Transactional
    public Map<String, Object> updateBusinessCoupon(CouponReDto couponReDto) {
        Integer couponId = couponReDto.getId();
        BmsDxCoupon bmsDxCoupon = bmsDxCouponDao.findByIdAndIsDelete(couponId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxCoupon == null){
            return ResultMapHelper.result(ResultCode.CODE_COUPON_NO_EXIST,ResultMsg.CODE_COUPON_NO_EXIST);
        }
        BmsDxCoupon newCoupon = new BmsDxCoupon();
        BeanUtils.copyProperties(bmsDxCoupon,newCoupon);
        bmsDxCoupon.setIsDelete(Constants.COMMON_FLAG_TRUE_INT);
        bmsDxCouponDao.save(bmsDxCoupon);
        BeanUtils.copyProperties(couponReDto,newCoupon,BeanUtils.getNullPropertyNames(couponReDto));
        newCoupon.setId(null);
        //特殊数据处理
        updateHandleSpeData(newCoupon,couponReDto);
        bmsDxCouponDao.save(newCoupon);
        return ResultMapHelper.success(newCoupon,ResultMsg.UPDATE_SUCCESS);
    }

    /**
     * @Description 特殊数据处理
     * @Param BmsDxCoupon
     * @Param couponReDto
     * @Author: cfx
     * @Date: 2019/9/22
     */
    private void updateHandleSpeData(BmsDxCoupon newCoupon, CouponReDto couponReDto) {
        //处理时间
        Date startTime = DateTimeUtils.converStringToDate(couponReDto.getStartTime());
        Date endTime = DateTimeUtils.converStringToDate(couponReDto.getEndTime());
        newCoupon.setStartTime(startTime);
        newCoupon.setEndTime(endTime);
    }

    public Map<String, Object> openCoupon(Integer userId,Integer businessId) {
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        /*if(!bmsUserBusinessAuthService.checkBusinessIsAuth(businessId)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_AUTH,"店铺未认证");
        }*/
        //查看商家是否绑定支付宝
        if(!bmsBusinessinfoService.checkBusinessHavingPayInfo(businessId)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_110,ResultMsg.CODE_ERROR_110);
        }
        //查看商家是否已经开通线上买单
        BmsDxCoupon bmsDxCoupon = null;
        List<BmsDxCoupon> bmsDxCoupons = bmsDxCouponDao.findByBmsBusinessIdAndType(businessId,Constants.COUPON_ONLINE);
        if(!(bmsDxCoupons != null && bmsDxCoupons.size() > 0)){
            bmsDxCoupon = new BmsDxCoupon();
            bmsDxCoupon.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
            bmsDxCoupon.setType(Constants.COUPON_ONLINE);
            bmsDxCoupon.setBmsBusinessId(businessId);
            bmsDxCoupon.setIsOffline(Constants.COMMON_FLAG_FALSE_INT);
        }else {
            bmsDxCoupon = bmsDxCoupons.get(0);
            bmsDxCoupon.setIsDelete(Constants.COMMON_FLAG_TRUE_INT);
            bmsDxCoupon.setIsOffline(Constants.COMMON_FLAG_TRUE_INT);
        }
        bmsDxCouponDao.save(bmsDxCoupon);
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    public boolean checkIsOpenCoupon(Integer businessId){
        if(!bmsBusinessinfoService.checkBusinessHavingPayInfo(businessId)){
            return false;
        }
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("bmsBusinessId",businessId);
        conditionMap.put("type",Constants.COUPON_ONLINE);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("isOffline",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsDxCoupon> bmsDxCoupons = bmsDxCouponDao.findAll(new SpecificationUtils(conditionMap));
        if(!(bmsDxCoupons != null && bmsDxCoupons.size() > 0)){
            return false;
        }
        return true;
    }

    public Map<Integer,Integer> checkIsOpenCoupon(Set<Integer> businessIds){
        Map<Integer,Integer> bmsDxCouponOpenMap = new HashMap<>();
        if(businessIds.size() > 0){
            Map<Integer,BmsDxCoupon> bmsDxCouponMap = getBmsCouponMap(businessIds,Constants.COUPON_ONLINE);
            Map<Integer, BmsBusinessInfo> bmsBusinessInfoMap = bmsBusinessinfoService.getBmsBusinessInfoMap(businessIds);
            for(Integer buinessId : businessIds){
                if(bmsDxCouponMap.containsKey(buinessId) && bmsBusinessInfoMap.containsKey(buinessId)){
                    bmsDxCouponOpenMap.put(buinessId,Constants.COMMON_FLAG_TRUE_INT);
                }
            }
        }
        return bmsDxCouponOpenMap;
    }

    public Map<Integer,BmsDxCoupon> getBmsCouponMap(Set businessIds,Integer couponType){
        Map<Integer,BmsDxCoupon> bmsDxCouponMap = new HashMap<>();
        List<BmsDxCoupon> bmsDxCoupons = bmsDxCouponDao.findByBmsBusinessIdInAndType(businessIds,Constants.COUPON_ONLINE);
        if(bmsDxCoupons != null && bmsDxCoupons.size() > 0){
            for(BmsDxCoupon bmsDxCoupon : bmsDxCoupons){
                bmsDxCouponMap.put(bmsDxCoupon.getBmsBusinessId(),bmsDxCoupon);
            }
        }
        return bmsDxCouponMap;
    }
}
